package com.it.schoolbookshop_back.controller;

import com.it.schoolbookshop_back.entities.po.Result;
import com.it.schoolbookshop_back.entities.po.User;
import com.it.schoolbookshop_back.service.UserService;
import com.it.schoolbookshop_back.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户资料控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/profile")
public class ProfileController {

    @Autowired
    private UserService userService;

    /**
     * 获取当前登录用户的详细信息
     * 需要token验证
     * @return 用户详细信息
     */
    @GetMapping
    public Result<Map<String, Object>> getMyProfile() {
        // 从ThreadLocal中获取当前登录用户ID
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return Result.failed(401, "未登录或token已过期");
        }
        
        // 查询用户信息
        User user = userService.getUserById(userId);
        if (user == null) {
            return Result.failed("用户不存在");
        }

        // 获取用户余额并格式化
        BigDecimal balance = BigDecimal.valueOf(user.getBalance());
        if (balance == null) {
            balance = new BigDecimal("0.00");
        }
        BigDecimal processedBalance = balance.setScale(2, RoundingMode.HALF_EVEN);
        
        // 构建返回数据
        Map<String, Object> profileData = new HashMap<>();
        profileData.put("username", user.getUsername());
        profileData.put("real_name", user.getRealName());
        profileData.put("department", user.getDepartment());
        profileData.put("student_id", user.getStudentId());
        profileData.put("email", user.getEmail());
        profileData.put("phone", user.getPhone());
        profileData.put("wechat", user.getWechat());
        profileData.put("bio", user.getBio());
        profileData.put("bookCount", user.getBookCount());
        profileData.put("soldCount", user.getSoldCount());
        profileData.put("boughtCount", user.getBoughtCount());
        profileData.put("favoriteCount", user.getFavoriteCount());
        profileData.put("avatar", user.getAvatarType() != null ? true : false);
        profileData.put("balance", processedBalance);
        profileData.put("address", user.getAddress());

        return Result.success(profileData);
    }
    
    /**
     * 修改用户资料
     * 需要token验证
     * @param profileData 要修改的资料
     * @return 修改结果
     */
    @PutMapping
    public Result<Map<String, Object>> updateProfile(@RequestBody Map<String, Object> profileData) {
        // 从ThreadLocal中获取当前登录用户ID
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return Result.failed(401, "未登录或token已过期");
        }
        
        // 查询用户信息
        User user = userService.getUserById(userId);
        if (user == null) {
            return Result.failed("用户不存在");
        }
        
        // 更新可以修改的字段
        if (profileData.containsKey("real_name")) {
            user.setRealName((String) profileData.get("real_name"));
        }
        if (profileData.containsKey("department")) {
            user.setDepartment((String) profileData.get("department"));
        }
        if (profileData.containsKey("student_id")) {
            user.setStudentId((String) profileData.get("student_id"));
        }
        if (profileData.containsKey("email")) {
            user.setEmail((String) profileData.get("email"));
        }
        if (profileData.containsKey("phone")) {
            user.setPhone((String) profileData.get("phone"));
        }
        if (profileData.containsKey("wechat")) {
            user.setWechat((String) profileData.get("wechat"));
        }
        if (profileData.containsKey("bio")) {
            user.setBio((String) profileData.get("bio"));
        }
        if (profileData.containsKey("address")) {
            user.setAddress((String) profileData.get("address"));
        }
        
        // 调用服务层保存修改
        boolean success = userService.updateUser(user);
        if (!success) {
            return Result.failed("更新个人资料失败");
        }
        
        // 构建返回数据
        Map<String, Object> updatedProfile = new HashMap<>();
        updatedProfile.put("username", user.getUsername());
        updatedProfile.put("real_name", user.getRealName());
        updatedProfile.put("department", user.getDepartment());
        updatedProfile.put("student_id", user.getStudentId());
        updatedProfile.put("email", user.getEmail());
        updatedProfile.put("phone", user.getPhone());
        updatedProfile.put("wechat", user.getWechat());
        updatedProfile.put("bio", user.getBio());
        updatedProfile.put("address", user.getAddress());
        
        return Result.success("个人资料更新成功", updatedProfile);
    }

    /**
     * 上传用户头像
     * 需要token验证
     * @param file 头像文件
     * @return 上传结果
     */
    @PostMapping("/uploadAvatar")
    public Result<Map<String, Object>> uploadAvatar(@RequestParam("file") MultipartFile file) {
        // 从ThreadLocal中获取当前登录用户ID
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return Result.failed(401, "未登录或token已过期");
        }
        
        // 检查文件是否为空
        if (file == null || file.isEmpty()) {
            return Result.failed("请选择要上传的头像文件");
        }
        
        // 检查文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return Result.failed("只支持上传图片文件");
        }
        
        // 检查文件大小（限制为2MB）
        if (file.getSize() > 2 * 1024 * 1024) {
            return Result.failed("头像文件大小不能超过2MB");
        }
        
        try {
            // 获取文件内容
            byte[] avatarData = file.getBytes();
            String avatarType = contentType;
            
            // 更新用户头像
            boolean success = userService.updateUserAvatar(userId, avatarData, avatarType);
            if (!success) {
                return Result.failed("头像上传失败");
            }
            
            // 构建返回数据
            Map<String, Object> result = new HashMap<>();
            result.put("message", "头像上传成功");
            result.put("avatarType", avatarType);
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.failed("头像上传失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户头像
     * 需要token验证
     * @return 头像数据和类型
     */
    @GetMapping("/downloadAvatar")
    public Result<Map<String, Object>> downloadAvatar() {
        // 从ThreadLocal中获取当前登录用户ID
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized();
        }
        
        try {
            // 获取用户信息
            User user = userService.getUserById(userId);
            if (user == null) {
                return Result.failed("用户不存在");
            }
            
            // 检查是否有头像
            byte[] avatarData = user.getAvatar();
            String avatarType = user.getAvatarType();
            
            if (avatarData == null || avatarType == null) {
                return Result.failed("用户未设置头像");
            }
            
            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("avatar", avatarData);
            data.put("avatarType", avatarType);
            
            return Result.success("获取头像成功", data);
        } catch (Exception e) {
            log.error("获取头像失败, 用户ID: {}, 错误: {}", userId, e.getMessage(), e);
            return Result.failed("获取头像失败：" + e.getMessage());
        }
    }

    /**
     * 修改用户密码
     * 需要token验证
     * @param passwordData 包含旧密码和新密码的数据
     * @return 修改结果
     */
    @PostMapping("/modifyPassword")
    public Result<Map<String, Object>> modifyPassword(@RequestBody Map<String, String> passwordData) {
        // 从ThreadLocal中获取当前登录用户ID
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized();
        }
        
        try {
            // 获取参数
            String oldPassword = passwordData.get("oldPassword");
            String newPassword = passwordData.get("newPassword");
            
            // 参数验证
            if (oldPassword == null || oldPassword.trim().isEmpty()) {
                return Result.validateFailed("请输入旧密码");
            }
            if (newPassword == null || newPassword.trim().isEmpty()) {
                return Result.validateFailed("请输入新密码");
            }
            if(oldPassword.equals(newPassword)){
                return Result.validateFailed("新密码不能和旧密码相同");
            }
            
            // 获取用户信息
            User user = userService.getUserById(userId);
            if (user == null) {
                return Result.failed("用户不存在");
            }
            
            // 验证旧密码
            if (!userService.verifyPassword(userId, oldPassword)) {
                return Result.failed("旧密码不正确");
            }
            
            // 修改密码
            boolean success = userService.updatePassword(userId, newPassword);
            if (!success) {
                return Result.failed("密码修改失败");
            }
            
            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("message", "密码修改成功");
            
            return Result.success(data);
        } catch (Exception e) {
            log.error("修改密码失败, 用户ID: {}, 错误: {}", userId, e.getMessage(), e);
            return Result.failed("密码修改失败：" + e.getMessage());
        }
    }
} 